LOGOUT
HELP
Richard Mansfield
Printing This Lesson
Select what you’d like to include when you print, and then click the Print Lesson button:
Text, images and activities (IE users only)
Text and images
Text only
Saving This Lesson
For instructions on saving this lesson (shown below), please select the browser you're using.
Introduction
Welcome back! In today's lesson, we'll explore a few more basic components of XML:
And you'll also start constructing the cookbook project. You'll soon see how much fun it is to create an app using the VS editor and the Visual Basic (VB) programming language! This powerhouse pair has taught computer programming to both amateurs and professionals for decades. It's the best way to understand (and personalize) your computer.
And even if you don't plan to make a career of it, you'll learn the secret: Many people write programs for fun, for recreation, and to create custom apps. Getting paid to do it is a bonus.
What's the Difference Between VS and VB?
Visual Studio (VS) is Microsoft's large programming suite. It contains several computer languages, including Visual Basic (VB), the language we use in this course. So throughout the course, I'll ask you to run VS, and when you choose the cookbook project, VS will automatically open the VB editor where you write your programming. VS does this because it recognizes that VB is the programming language you're using to write the cookbook program.
Here's a mystery: I don't know why it happened this way, but it's the math departments that teach programming in most schools. If you have any idea why this is, please visit the Discussion Area and let me know. Studies have shown that some of the best natural programmers are music or English majors. And if you think about it, that makes sense. Programming is a form of communication.
Programming isn't about math any more than libraries are about math. True, you can read books about math, and if you work for NASA, your programs will certainly focus on math too . . . rocket trajectories, landing on Mars, things like that.
But most programs, like most books, simply aren't about math. The cookbook program, for example, is a totally math-free zone.
With that in mind, let's get started. We'll begin with a look at the differences between XML and HTML.
Comparing XML and HTML
XML stands for extensible markup language.
We've been using the acronym XML, but so far, we haven't discussed what these three letters mean. I've delayed explaining this until now for a reason. And that's because it's difficult to understand XML without also describing HTML. So now let's take a look at both XML and HTML.
Make sense?
To better understand how powerful XML is, let's take a look at HTML.
HTML stands for hypertext markup language. It's the language used to tell a browser how to display and manipulate information. Hypertext refers to those links you click that take you to a different Web page or a different location in a document. Now you know now what markup and language refer to. (See above.)
Most people think of HTML as a parent of XML. XML can do quite a bit more than HTML. For one thing, HTML isn't extensible. It only has a set of predefined tags, like <h1></h1> (displays a large headline), or bgcolor (changes the background color of a Web page). You can't rename the <h1> tag.
Also, HTML focuses on formatting, telling a browser like Internet Explorer how you want to display things—where on the page to place a picture, how large a headline should be, what colors to use, where to display a link to another Web page, and so on.
XML Goes Beyond Formatting
XML can do all that too, but it goes far beyond mere page design. As you'll see throughout this course, XML can manipulate data in many powerful ways. Here's a look at what it can do:
And we aren't just talking about documents. Some like to define XML very narrowly, limiting it to XML documents alone. But most people take the wider view that embraces the set of technologies that expand XML's capabilities beyond merely storing and tagging content in documents. Throughout this course, you'll explore all the major XML tools, including XSL, XPath, XSLT, Schema, and SVG graphics.
Examining HTML Code
Okay, let's take a look at some HTML code. It looks a lot like XML, with tags enclosing content.
<html> <title>Sample HTML</title> <body bgcolor="lightblue"> <h1>Heading 1</h1> <h2>Heading 2</h2> <h3>Heading 3</h3> <hr> <p>Here is some text.</p> </body> </html>
Notice a couple of things here. The <hr> tag means draw a horizontal rule (line). But this <hr> element has no end tag. HTML permits this, whereas XML insists on end tags. End tags are also sometimes missing from the HTML <p> tag (<p> stands for new paragraph).
HTML is less strict than XML. Put another way, HTML is messier—rules are broken, different browsers sometimes interpret (or parse) HTML in different ways. And as a result, a Web page can look various ways depending on which browser you use, though standards have been improving.
Here are the main things to remember about HTML as compared to XML:
Not too difficult when we break it down that way, right? Let's move on to the next chapter where we'll talk about adding comments and attributes in XML.
Adding Comments and Attributes
Before we get started, try this quick challenge to see how much you remember about the basic similarities and differences between XML and HTML.
Choose between HTML and XML! Select the button next to the sentence, and then select its corresponding language.
Adding Comments
Another similarity between HTML and XML is that they both allow you to insert comments in your code. Comments are simply for the benefit of the programmer. They're not instructions to the computer.
Both HTML and XML use the same start and end tags to enclose a comment:
<!-- -->
Here's an example showing how to add a comment to the cookbook program:
<cookbook> <!--Maybe add a separate "ingredients" element later? Then we could do multiplication or division to adjust the recipe for different portions--> <recipe> <title>The Secret to Perfect Coleslaw</title> <instructions>To prevent the slaw from getting runny or turning grey, mix 1 Tablespoon of kosher salt into the shredded cabbage, and let it sit for 1-4 hours. You're briefly pickling it. Then rinse the cabbage in a colander, and gently press it to drain it. Roll gently in paper towels to dry it further. Now add your dressing. Most restaurants know all this. Most home cooks don't. Keeps well for a week!</instructions> </recipe> </cookbook>
Why Use Comments?
Programmers write comments within their code for the same reason that actors write notes in their scripts. It helps clarify what's going on or suggests improvements. Comments can include suggestions to yourself (or other programmers) about possible future changes to the program.
But most often, comments describe what's happening in the code. Sometimes you'll come back to modify your programming months or years later, or some other programmer will work with your code. In these situations, comments can be a lifesaver.
Given that XML code is self-documenting—with all those descriptive tags—you may not need to add many comments to your XML documents. After all, <title> and <instructions> make it pretty clear what those elements of a recipe are.
But in other code you write, such as VB programs, comments are often helpful (sometimes even necessary!) to clarify what the heck is going on.
Remember that XML, HTML, or any other programming language completely ignores your comments. For example, when a browser displays HTML, or a sporting goods store uses XML to reorder stock, the computer just skips over any comments.
Here are a few things to remember when adding comments to XML code:
?xml version="1.0"?
<title>The Circus Adventure<!--Put this one in the children's section--></title>
<title>The Circus Adventure</title><!--Put this one in the children's section-->
<!--Expand this element -- maybe include a sell-by date-->
All right, you've got the theory. Let's take a look at adding comments in practice.
The editor automatically adds the end tag, with the blinking insertion cursor right between the two comment tags, like this:
<!--These recipes are used with the Cookbook program-->
Great work! Now watch as I add a comment to some XML code. (And remember, if you have questions at any point during this course, you can find me in the Discussion Area.)
Okay. We want to open the recipes.xml file, so double-click your Cookbook folder, and then just double-click recipes.xml, and that will open it in Visual Studio. Now, the blinking insertion cursor always appears at the very first line of code, so move it down one line to line 2, and then press Enter to give yourself a blank line.
This blank line is where we want to enter our comment, so move the cursor back up. Use the arrow or use your mouse. And then type in the less-than symbol. This opens a list of three options. You want the first one, which is the comment, which is an exclamation point followed by two dashes, so double-click that to insert it.
Notice how the insertion cursor is now moved in between the start comment and end comment symbols, right where you want to insert your comment. So type in your comment here, and there you go.
You've added a comment here that will be ignored by Visual Studio and by any other program that manages XML, but on the other hand, it will allow you to see what you're doing. It tells you, in this case, that we're using these recipes. This XML file is being used with our Cookbook program, and that's it.
END TRANSCRIPT
Okay, now let's look at adding attributes.
Replacing Elements With Attributes
We've worked with elements and tags, but attributes are the final major feature of XML code. Attributes are optional, and we won't use them at all in the cookbook project. But because they're sometimes used in XML documents, you should know what they look like and what they do.
Attributes are similar to elements but more compact. An element contains crucial data such as a company's address, but an attribute contains less important information—information that you could leave out without causing serious damage. For example, you could put into an attribute your preferred text size for displaying the data.
In other words, you can't leave out the address. It's essential information. But you can omit your text size preference—displaying the text in a different size won't ruin your project.
You place attributes inside an element tag, like this:
<customeraddress textsize="12">
To further clarify the distinction between an element and an attribute, let's first look at a typical element with two children:
<customer> <firstname>Caesar</firstname> <lastname>Gomes</lastname> </customer>
Children and Parent Elements
In case you've gotten rusty, child elements are nested within parent elements. For example, a <tire> child element would nest within its parent <car> element. A child element is contained within its parent element because it's part of the parent in the same sense that a wheel is part of a car, not vice versa. Here's how nesting looks:
<car> <wheel></wheel> </car>
Now let's add an attribute:
<customer fontsize ="10" > <firstname>Caesar</firstname> <lastname>Gomes</lastname> </customer>
As you can see, an attribute has four qualities that distinguish it from an element:
Attributes do save space. In this example, because you made the font size an attribute, you didn't have to add a start and end tag for it, as an element would require.
But saving space doesn't matter at all to us, because our computers' memory can hold far more recipes than you'll ever put into your cookbook. However, large companies, not to mention government agencies like the IRS, face serious challenges managing the enormous amount of data they store and manipulate. For them, space (or scale as computer people call it) is a major consideration.
The Dark Side of Attributes
Although attributes are useful in some situations, like massive data storage, you do pay a price when using them. Let's take a look.
Wow! Unreadable, unstructured, un-programmable . . . you'd have to be barking mad to ever use attributes, right? Indeed, some experts do advise that you avoid them completely. But to be fair, attributes do have a useful purpose in addition to saving space. If you wish, for instance, you can use attributes to hold secondary, optional data, like font size. And later in this course, you'll practice using attributes for some specialized XML programming.
Although some XML programmers use attributes in additional ways, their primary value is to store brief, optional data. As you gain experience with XML, you might find other uses for attributes. To some extent, they're a matter of taste.
Okay, roll up your sleeves, and get ready to create the cookbook program!
Building the Cookbook Program
In Lesson 1, you created an XML document containing a recipe or two. Your goal in this chapter is to begin designing the program that will process that data.
One good way to start designing a VB program is by building the user interface (UI)—the window where the user will view, search, add, delete, and edit recipes. In future lessons, you'll be adding these features.
For now, though, your programming task is somewhat more modest: to put a button named Exit on the window and to write programming code that stops the cookbook program from running when the user clicks that button.
What Are Controls?
The VB toolbox is full of components like buttons and text boxes that you can add to a form to create the UI. These components are called controls.
Follow these steps to get the VS editor ready:
Okay. Let's start our user interface and design the form and one button for this lesson. We'll go ahead, start Visual Studio and then look for the Recent title, which is a list of any projects you've worked on recently in Visual Studio. Double-click Cookbook, and it opens and shows a last file we worked on, which was recipe.xml. Well, we don't need that for this user interface design, so go ahead and click the X to close it.
Now you'll see Form 1. Our cookbook only uses one window, so we'll stick with Form 1 throughout this entire course. But we need it to be larger so that it's easier for the user to work with and we can put various controls on it. So take the little white box down in the corner and drag your form until it's large and fills most of the Design window. Notice these little handles, these little white squares. They're a way for you to resize, or in some cases, reposition an object, including the form or any of the controls you put on it.
So now let's add an Exit button. Click on the Toolbox to see the list of various controls that you can add to your user interface. We want a button that the user can click to leave the program and shut down the cookbook, so double-click the Button, and then the Toolbox will disappear when you move your mouse, and you'll see that a button has been added to Form 1. Now, this is an Exit button, and it's traditional in Windows for the Exit button to be in the lower right corner, so we'll drag it down there, and then take one of its handles and stretch it until it's fairly large. You can also drag the button to position it wherever you want, but this looks like a good size right here.
Only one control at a time can have what's called the focus. That means that it has those little handles around it and you can add properties to it from the Properties window, or you can drag it, or you can move it. And the form itself can also get the focus. If you click the form, it suddenly gets the handles, and the handles are gone from the button. But click the button, select it, it gets the focus.
It's important to remember that when you're giving the focus to an object in the Design window, its properties will appear in the Properties list over here. This Properties window is often used because you can change the qualities of something. But notice when I click the form to give it the focus, the properties change because the form has different properties than the button control. So the Properties window responds to whichever control or object has the focus at any given time, and only one can have the focus.
Double-click Button in the Toolbox, and then move your mouse pointer away from the Toolbox to autohide it. A button will appear on your form.
It's traditional to locate an Exit button in the lower right of a window. So let's move that button down.
Drag the button down to the lower right.
Also, it's a bit small, so drag one of the small white squares around the button to enlarge it.
What if There Are No Small Squares Around the Button?
If the squares are missing from the button, that means you've clicked something else and the button is no longer selected. If this happens, just click the button. The selection handles will reappear, and you can now resize or drag the button. Also, when you select a control, the Properties window lists all its properties and their values.
Working With the Properties Window
Take a look at the Properties Window on the right. It lists all the qualities that a button can have, including size, location, color, and typeface. You can change these in the Properties window. Let's try it.
Now, let's change the button's Name property in the Properties window. When you write code, you use its Name property to refer to this particular button. The name is just for you, the programmer. The user never sees it.
Although you can describe entering recipes (data) or designing the cookbook form (UI) as programming, here's a stricter definition of the word programming:
Programming: Writing code to tell the computer how to behave
That's what we'll do now.
You've just left the design window and opened the editor's code window.
Notice that the editor added a new tab, currently colored yellow, named Form1.vb for the code window. You can freely switch back and forth between the code and design windows by clicking their respective tabs, or by right-clicking and choosing view designer or view code from the context menu.
The editor has automatically filled in some housekeeping details for you in the code window:
1 Public Class Form1 2 3 Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click 4 5 End Sub 6 End Class
Let's focus on Line 3. Translated, it says, "This subroutine is named btnExit_Click, and this sub—you guessed it—handles what the computer does if a user clicks this button."
Let's Break That Down
You can ignore the stuff inside the parenthesis, the sender and EventArgs. They're rarely used in ordinary programming. You can also ignore the two lines involving the class. They refer to a specialized, advanced kind of software development known as object-oriented programming or OOP. You won't need to worry about OOP in this course, or possibly ever if you remain an amateur programmer, working alone. You might enjoy OOP, but it's a sophisticated technique and is especially useful for large programs built by teams.
Your new button behaves like any other Windows button—the user can click it to make something happen. This button shuts the cookbook program down.
But button controls can trigger many kinds of behaviors, not just an exit. You, the programmer, write some code that tells VB what you want to happen when the user clicks each particular button.
Subdividing Programs
A computer program can't be one huge, long list of instructions. That's unwieldy. So programs are broken into small sections called subs (also known as procedures or functions). The Sub and End Sub code lines mark the start and end of each limited task that the program will carry out. So you write your code lines within a series of Sub and End Sub containers. Each container does one, small task.
A sub (short for subroutine) usually holds fewer than say 40 lines of code. By subdividing the program into small units like this, you can write, read, or modify the program more easily.
For example, recall that the finished cookbook program will do several tasks for the user: display, search, add, delete, and edit recipes. Each of these tasks will be contained within its own individual Sub…End Sub code unit.
And subdividing your code into these isolated units also makes it far easier for you to fix errors. If something is wrong with printing, for example, you're likely to find the problem in the sub that handles printing. It's the same idea as giving each member of the family a particular task before leaving for vacation. That way, each task is small enough to be manageable. Mom doesn't have to do everything. And if you get to the beach without any towels, you know it's time to talk to Jimmy about taking responsibility!
Lucky for you, VB uses many words you're already familiar with. You have an Exit button on your cookbook form. Now you need to write the code that makes this button do its job—shutting down the cookbook program.
The code you write to shut down a program is elegantly simple in VB. Just type in the word end, and VB will know what you want it to do.
So go ahead and type end between the Private Sub btnExit_Click and End Sub code lines, like this:
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click End End Sub
You can type end in lowercase if you wish, but the editor will uppercase the E to cue you that this word is a VB command, a part of VB's vocabulary. But unlike XML, VB ignores uppercase and lowercase. End is the same as end. VB is case-insensitive. VB capitalizes it just to make it easier for you to read the code.
How Many Words Are in VB's Vocabulary?
About 50 that you'll use most of the time. This is one reason that computer programming is often easier than many people believe. Mastery of a typical human language like English requires that you know at least 10,000-20,000 commonly used words. Estimates of the total number of words in English ranges from a quarter million to over a million.
Now for some real magic. You're going to execute your program and test it to see if it behaves the way you want it to. In the editor, you can simulate running your program by pressing the F5 key.
It's a very simple program at this point. It just starts and then sits there doing nothing while waiting for the user to click its sole button. And that button has only one instruction in the code behind it: End.
Congratulations, you've started a UI design, written code, and tested the code. Quite an accomplishment in this short time.
The VS editor is amazingly efficient, thanks to the hundreds of thousands of programmers who have suggested improvements to VS and VB over the past decades! And you should also be grateful to Microsoft's many busy programmers who have been polishing VS and VB all these years.
Summary
Well done! You covered a lot of ground in this lesson. You explored the differences between HTML, a formatting language, and XML, a more powerful language that does much more than merely describing how a Web page should look. You finished learning how to use the fundamental components of XML documents by working with comments and attributes. And you created the shell of the user interface you'll build throughout this course to manage and display your XML cookbook data.
Let's Chat!
Early on in this lesson, I mentioned that programming is a form of communication. And yet it's math departments that teach programming in most schools, as opposed to departments such as music or English. Stop by the Discussion Area, and share your thoughts on this idea of programming as communication.
Be sure to check out the FAQs and Supplementary Material links for this lesson. After you've taken the quiz and completed the assignment, meet me in Lesson 3 where we'll discuss the elements of programming and how computers and programs really work!
If you want to know more about how Web pages are constructed, this beginner's guide to HTML is a good place to start.
A: Good question! XML editors like the one in Visual Studio will usually alert you if an XML document isn't "well-formed"—for instance, if your XML code contains a violation of an XML rule, such as putting text content outside of tags or forgetting an end tag. HTML is less strict about its own rules. Here's some code from a sample HTML document:
<html> <head> <title>This shows up in a browser tab or title bar.</title> </head> <body> Content that's displayed on the Web page goes here </body> </html>
The <html>, <title>, and <body> tag pairs are supposedly mandatory, according to the rules. The <head> tags are optional.
But what happens if you leave out the </body> end tag, for example? Nothing. No warnings, no refusal to display the faulty code. The browser goes ahead and displays this page exactly as it would were the </body> end tag present in the code. So you can see how HTML is less exacting than XML!
For this lesson's assignment, you're going to practice using the Properties window to change the form's background color and text property (the title at the top of the form). Here are the steps:
Now your form has a new title at the top of the form—and a new color!
Watch this video to see me walk through the steps:
Let's tackle this assignment. Our goal here is to change the color of the form and also provide it with a title up in the top. So the first thing we need to do is go to the Design window. We were last working on the code, so we were here in the Code window, but to go to the Design window, you just press Shift, F7, and there you are.
We're changing the form's properties, so let's click the form to give it the focus. And before we do anything, I want you to take a close look up here at the top of the Properties window. Make sure that this alphabetical icon is selected—yellow, in other words—and also that this Properties icon is selected. Both of those need to be selected all throughout this course, and if they aren't, click them to make sure that they're yellow.
Now, to change the color of the form, scroll up until you see the BackColor property. Click it once. Don't double-click it. And then click the down arrow to see a list of possible colors you can choose. The InactiveCaption color is okay. Click that or any other color you prefer. I like this light blue. And if you're interested in even more color choices, go ahead and click the Custom tab here at the top of the list, and then you have a whole variety of choices. You can even click an empty one and change it to white, or in any case, DimGray, or whatever's interesting to you. What color you like is up to you. Just don't pick something really dark like black, because then you'll have a hard time seeing things on the form. So stick with something perhaps like InactiveCaption. That's the one I like.
Now, let's change the title of this form. By default, it's given the title Form 1, but we want to name it Cookbook. So scroll down until you see the Text property down here and click over there in the right side where you can enter information. And then select Form 1 and type over "Cookbook." And notice that as soon as you press Enter, it changes up here in the title. And that was the goal of this assignment.
Back to top